package com.lindroy.androidplayer.base.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.lindroy.androidplayer.utils.getViewBinding

/**
 * @author Lin
 * @date 2022/1/17
 * @function 用于分页请求的 Adapter
 */
abstract class BasePagingAdapter<T : Any, VB : ViewDataBinding>(
    private val lifecycleOwner: LifecycleOwner,
    diffCallback: DiffUtil.ItemCallback<T> = object : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem

        @SuppressLint("DiffUtilEquals")
        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem
    }
) : PagingDataAdapter<T, BasePagingAdapter.BindViewHolder<VB>>(diffCallback) {

    fun withFooter() = withLoadStateFooter(FooterAdapter { retry() })

    class BindViewHolder<M : ViewDataBinding>(var binding: M) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindViewHolder<VB> =
        getViewBinding<VB>(
            LayoutInflater.from(parent.context), parent, false, 1
        ).run {
            BindViewHolder(this)
        }

    override fun onBindViewHolder(holder: BindViewHolder<VB>, position: Int) {
        DataBindingUtil.bind<VB>(holder.itemView)?.lifecycleOwner = lifecycleOwner
        holder.binding.onBindViewHolder(getItem(position), position)
    }

//    protected open fun areItemsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem

//    protected open fun areContentsTheSame(oldItem: T, newItem: T) = oldItem == newItem


    abstract fun VB.onBindViewHolder(item: T?, position: Int)
}